<?php
/**
 * @author Amissah Gideon<kuulmek@yahoo.com>
 * @access public
 * @version 1.0
 */

class CustomersController extends AppController {
    # Controller Name to be used
       var $name = 'Customers';

      # Models to be used
       var $uses = array(
           'Customer',
           'Credit',
           'Country',
           'Region'
       );

       # set the layout to use
       var $layout = 'customers_layout';
       
       # set the name of this module
       var $moduleName = 'Customers';

       # Check the authenticity of the user
       function  beforeFilter() {
            parent::beforeFilter($this->moduleName);
            parent::setUpGlobalConfig();  
       }
       
       # Controller actions
       /**
        * This function displays all the users in the system
        * @name index
        * @param void
        * @return Array of data.
        * @access public
        */
       function index(){
           $customer_types_opt = $this->customer_types;
           $country_list = $this->Country->find('list', array(
               'fields' => array('Country.id', 'Country.name'),
               'recursive' => -1
           ));

           $region_list = $this->Region->find('list', array(
               'fields' => array('Region.id', 'Region.rname'),
               'recursive' => -1
           ));

           $page_title = 'Customers Managements';

           $this->set(compact('page_title','customer_types_opt','country_list','region_list'));
       }

       /**
        * This function add a new record to the database
        * @name add
        * @param void
        * @return Json data
        * @access public
        */
       function add(){
          # Get the user session data
          $loggedUser =  $this->Auth->user();
          # check whether the HTTP Request is an ajax request
          if($this->request->is('ajax')){
                 # disable the rendering of the layout
                 $this->autoRender = false;
                 $this->autoLayout = false;
                 # retrieve the model
                 $model = ucfirst($_POST['model']);
                 # Check the model
                 switch($model){
                      case 'Customer' :
                    	$upt_id = ($_POST['row_id'] != 'null') ? $_POST['row_id'] : false;
                    	$loggedUser_id = $loggedUser['id'];

                        if(isset($this->request->data['Customer']['date_of_commence'])){
                            $this->request->data['Customer']['date_of_commence'] = $this->covertDate($this->request->data['Customer']['date_of_commence'],'mysql');
                        }
                    	$this->request->data['Customer']['name'] = strtoupper($this->request->data['Customer']['name']);
                        $this->request->data['Customer']['contact_person'] = strtoupper($this->request->data['Customer']['contact_person']);
                    	$this->request->data['Customer']['address'] = strtoupper($this->request->data['Customer']['address']);
						$this->request->data['Customer']['city'] = strtoupper($this->request->data['Customer']['city']);
						$this->request->data['Customer']['physical_location'] = strtoupper($this->request->data['Customer']['physical_location']);
						$this->request->data['Customer']['comments'] = strtoupper($this->request->data['Customer']['comments']);
						
						if($upt_id){ /** Edit Customer*/
                            $this->request->data['Customer']['modified_by'] = $loggedUser_id;
                    		$this->Customer->id = $upt_id; 	
                    	}
                    	else{ /** New Customer*/
                            $this->request->data['Customer']['created_by'] = $loggedUser_id;
                    		$this->Customer->create();                    		
                    	}
                    	
                    	# save the data
                    	if($this->Customer->save($this->request->data)){
                            $data = array('id'=>$this->Customer->id);
                   			  return json_encode(array('code' => 0, 'data' => $data,'mesg' => __('Data Saved')));
                		}
                		else{
                			  return json_encode(array('code' => 1, 'mesg' => "Can't save customer data"));
                		}  
                      break;
                 }
          }
       }


    function import($customer_id = null){
        $this->layout = 'import_layout';
        $mesg = '';
        if ($this->request->is('post')) {
            $loggedUser =  $this->Auth->user();
            $loggedUser_id = $loggedUser['id'];
            $customer_id = $_POST['customer_id'];
            $result = $this->uploadFile($customer_id);
            if($result['status']){
                $this->Customer->save(array(
                    'id'=>$customer_id,
                    'pic_filename'=>$result['filename'],
                    'modified_by' => $loggedUser_id
                ));

                $mesg = $result['mesg'];
            }
            else{
                $mesg = $result['mesg'];
            }
        }

        $this->set(compact('mesg','customer_id'));
    }


    function uploadFile($customer_id){
        $raw_file_name = $_FILES['file-input']['name'];
        if (empty($raw_file_name)) {
            return array('status'=>false,'mesg'=>"No file selected.");
        }
        # folder path structure
        $folder = 'img/customers_files/';
        # setup directory pathname
        $folderAbsPath = WWW_ROOT . $folder;
        $folderRelPath = $folder;

        # create folders if it does not exist
        if (!is_dir($folderAbsPath)) {
            mkdir($folderAbsPath, 0777, true);
        }

        # get the file details
        $raw_file_name = str_replace(' ', '_',$_FILES['file-input']['name']);
        $raw_file_name = $customer_id."_".$raw_file_name;

        $rawFile = $folderAbsPath . basename($raw_file_name);

        // replace spaces with underscores
        $new_filename = $raw_file_name;
        $fileName = $rawFile;

        # check whether the file already exists or not
        if (!file_exists($fileName)) {
            # upload the file
            if (move_uploaded_file($_FILES['file-input']['tmp_name'], $fileName)) {
                return array('status'=>true,'mesg'=>"Customer's Picture has been uploaded!",'filename'=>$new_filename);
            } else {
                return array('status'=>false,'mesg'=>'Cannot upload picture');
            }
        }
        else {
            return array('status'=>false,'mesg'=>'File name already exist.');
        }
    }




    /**
        * This function load the add user form
        * @param void
        * @return html
        * @access public
        */
       function loadCustomer(){
            $this->autoRender = false;
            $this->autoLayout = false;
            
            /** Loading */
            $userData = $this->Customer->getCustomerById($_POST['data-id']);
            
            if($userData){                
                return json_encode(array('code' => 0, 'data' => $userData, 'mesg' => __('Data Found')));
            }
            else{
                return json_encode(array('code' => 1, 'data' => array(), 'mesg' => __('No Record Found')));
            }
       }

       
       
        #Delete Users via ajax
	    function deleteCustomers(){
			if($this->request->is('ajax')){
				$this->autoRender = false;
				$this->autoLayout = false;

                $loggedUser =  $this->Auth->user();
                $loggedUser_id = $loggedUser['id'];
                 
                $ids = $_POST['ids'];
                $modObj = ClassRegistry::init('Customer');
                $result = $modObj->updateAll(
					array('Customer.deleted' => "'y'",'Customer.modified_by' => $loggedUser_id),
					array('Customer.id' => $ids)
				);
				
				if($result){
					 echo json_encode(array('code' => 0, 'mesg' => __('Selected Customers have been successfully deleted')));
				}
				else{
					echo json_encode(array('code' => 1, 'mesg' => __('Selected Customers cannot be deleted')));
				}
             }
		}
       

       /**
        * @name
        * @param void
        * @return Json Data
        */
         function getCustomers(){
            # disable the rendering of the layout
            $this->autoRender = false;
            $this->autoLayout = false;
            
            /**  Get posted data */
            $page =      isset($_POST['page']) ? $_POST['page'] : 1 ; /** The current page */
            $sortname =  isset($_POST['sortname']) ? $_POST['sortname'] : 'id' ; /** Sort column */
            $sortorder = isset($_POST['sortorder']) ? $_POST['sortorder'] : 'desc' ; /** Sort order */
            $qtype =     isset($_POST['qtype']) ? $_POST['qtype'] : '' ; /** Search column */
            $search_query =     isset($_POST['query']) ? $_POST['query'] : '' ; /** Search string */
            $rp =        isset($_POST['rp']) ? $_POST['rp'] : 10 ;
            $limit = $rp;
            $start = ($page-1) * $rp;
            
            $condition_array = array('Customer.deleted' => 'n');
            if (!empty($search_query)){
                if($qtype == 'name'){
                    $condition_array = array(
                       'Customer.name LIKE' => $search_query . '%',
                       'Customer.deleted' => 'n'
                     );
                }
                if($qtype == 'region_name'){
                    $condition_array = array(
                        'Region.rname LIKE' => $search_query . '%',
                        'Customer.deleted' => 'n'
                    );
                }
                else{
                    $condition_array = array(
                       "Customer.$qtype LIKE" => $search_query . '%',
                       'Customer.deleted' => 'n'
                     );
                }
            }
            
            
            $fields = array('Customer.id','Customer.name','Customer.contact_person','Customer.phone_number','Customer.email','Customer.address','Customer.city','Customer.region_id');
            $contain = array('Region'=>array('fields'=>array('Region.id','Region.rname')));
            $users = $this->Customer->find('all', array('fields'=>$fields,'contain'=>$contain,'conditions' => $condition_array,'order' => "Customer.$sortname $sortorder",'limit' => $start.','.$limit,'recursive' => 1));
            $usersCount  = $this->Customer->find('count', array('contain'=>$contain,'conditions' => $condition_array,'recursive' => 1));
            
            $total_records = $usersCount;
            
            if($users){
                $return_arr = array();
                foreach ($users as $obj){
                   /*$total_credit = count($obj['Credit']);
                   $total_cost = 0.00;
                   foreach($obj['Credit'] as $creditObj){
                        $total_cost += $creditObj['cost'];
                   }*/

                   $return_arr[] = array(
                        'id' => $obj['Customer']['id'],
                        'cell' => array(
                            $obj['Customer']['id'], 
                            $obj['Customer']['name'],
                            $obj['Customer']['contact_person'],
                            $obj['Customer']['phone_number'], 
                            $obj['Customer']['email'],
                            $obj['Customer']['address'],
                            $obj['Customer']['city'],
                            $obj['Region']['rname']
                            /*$total_credit,
                            number_format($total_cost, 2, '.', '')*/
                        )
                   );                  
                }
                return json_encode(array('success' => true, 'total'=>$total_records, 'page' => $page,'rows' => $return_arr));
            }
            else{
               return json_encode(array('success' => false, 'total'=>$total_records, 'page' => $page, 'rows' => array()));
            }       		
             
        }



    /**
     * @name
     * @param void
     * @return Json Data
     */
    function getCustomersCredits(){
        # disable the rendering of the layout
        $this->autoRender = false;
        $this->autoLayout = false;

        /**  Get posted data */
        $page =      isset($_POST['page']) ? $_POST['page'] : 1 ; /** The current page */
        $sortname =  isset($_POST['sortname']) ? $_POST['sortname'] : 'id' ; /** Sort column */
        $sortorder = isset($_POST['sortorder']) ? $_POST['sortorder'] : 'desc' ; /** Sort order */
        $qtype =     isset($_POST['qtype']) ? $_POST['qtype'] : '' ; /** Search column */
        $search_query =     isset($_POST['query']) ? $_POST['query'] : '' ; /** Search string */
        $rp =        isset($_POST['rp']) ? $_POST['rp'] : 10 ;
        $limit = $rp;
        $start = ($page-1) * $rp;

        $condition_array = array('Customer.deleted' => 'n');
        if (!empty($search_query)){
            if($qtype == 'name'){
                $condition_array = array(
                    'Customer.name LIKE' => $search_query . '%',
                    'Customer.deleted' => 'n'
                );
            }
            else{
                $condition_array = array(
                    "Customer.$qtype LIKE" => $search_query . '%',
                    'Customer.deleted' => 'n'
                );
            }
        }


        $fields = array('Customer.id','Customer.name');
        $users = $this->Customer->find('all', array('fields'=>$fields,'conditions' => $condition_array,'order' => "Customer.$sortname $sortorder",'limit' => $start.','.$limit,'recursive' => 1));
        $usersCount  = $this->Customer->find('count', array('conditions' => $condition_array,'recursive' => -1));

        //echo debug($users);

        $total_records = $usersCount;

        if($users){
            $return_arr = array();
            foreach ($users as $obj){

                $return_arr[] = array(
                    'id' => $obj['Customer']['id'],
                    'cell' => array(
                        $obj['Customer']['id'],
                        $obj['Customer']['name']
                    )
                );
            }
            return json_encode(array('success' => true, 'total'=>$total_records, 'page' => $page,'rows' => $return_arr));
        }
        else{
            return json_encode(array('success' => false, 'total'=>$total_records, 'page' => $page, 'rows' => array()));
        }

    }


}